package com.jxmcloud.business.cut.json;

import com.xlcloud.platform.util.PublicUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.jxmcloud.business.cut.service.json.IConfigStartService;
import com.jxmcloud.business.cut.vo.json.ConfigStartVo;
import com.jxmcloud.business.cut.model.json.ConfigStart;

@Slf4j
@Component
public class DataConfigStartLoader {
    @Resource
    private IConfigStartService configStartService;
    //
    private Map<Integer, ConfigStartVo> configStartMap = Collections.emptyMap();

    public boolean loadFromDb() {
        try {
            Map<Integer, ConfigStartVo> tempMap = new HashMap<>();

            List<ConfigStart> list = this.configStartService.list();
            if (PublicUtil.isNotEmpty(list)) {
                List<ConfigStartVo> configStartVos = PublicUtil.copyList(list, ConfigStartVo.class);
                tempMap = configStartVos.stream().collect(Collectors.toMap(k -> k.getId(), v -> v));
            }
            
            // 创建不可修改的Map
            log.info("加载configStart表数据成功！");
            this.configStartMap = Collections.unmodifiableMap(tempMap);
            return true;
        } catch (Exception e) {
            log.error("加载数据失败！{}", e);
        }
        return false;
    }

    public Map<Integer, ConfigStartVo> getConfigStartMap() {
        return this.configStartMap; // 返回不可变Map
    }

    //
    public ConfigStartVo getConfigById(Integer id) {
        ConfigStartVo data = this.configStartMap.get(id);
        if (ObjectUtil.isNull(data)) {
            return null;
        }
        return data;
    }

    public boolean reloadFromDb() {
        this.configStartMap = new HashMap<>();
        return this.loadFromDb();
    }
}
